package com.gzhryc.shared_device.oem.code.profit.service;

import com.gzhryc.common.StringTools;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.shared_device.oem.code.member.dao.db.MemberBusinessOrder;
import com.gzhryc.shared_device.oem.code.member.services.MemberBusinessOrderService;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlacePhysicalStore;
import com.gzhryc.shared_device.oem.code.place.dao.db.PlaceProfitUser;
import com.gzhryc.shared_device.oem.code.place.services.PlacePhysicalStoreService;
import com.gzhryc.shared_device.oem.code.place.services.PlaceProfitUserService;
import com.gzhryc.shared_device.oem.code.profit.dao.BusinessOrderUserDao;
import com.gzhryc.shared_device.oem.code.profit.service.dto.BusinessOrderUserSearch;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.code.profit.dao.db.BusinessOrderUser;

import java.sql.SQLException;
import java.util.*;

public class BusinessOrderUserService {

    static Logger log = Logger.getLogger(BusinessOrderUserService.class);

    public static BusinessOrderUserService self(Date date) {
        return MultiDBTools.getService(BusinessOrderUserService.class, date);
    }

    public static BusinessOrderUserService self(String jdbcKey,Date date) {
        return MultiDBTools.getService(jdbcKey,BusinessOrderUserService.class, date);
    }

    BusinessOrderUserDao dao;

    public BusinessOrderUserService(String jdbcKey,Date date) {
        dao = new BusinessOrderUserDao(jdbcKey,date);
    }

    public List<BusinessOrderUser> findBySearch(BusinessOrderUserSearch search, Integer pageNo, Integer pageLimit){
        Conditions conditions = dao.buildConditions(search);
        conditions.and().likeBoth("tradeNo",search.getTrim()).or().likeBoth("placeName",search.getTrim());
        conditions.desc("createDate");
        try {
            return dao.findByCondition(conditions,pageNo,pageLimit);
        } catch (SQLException e) {
            log.error(e.getMessage(),e);
        }
        return null;
    }

    public List<BusinessOrderUser> findJoinByTradeNo(String tradeNo){
        if(StringTools.isNotBlank(tradeNo)) {
            Conditions conditions = new Conditions(BusinessOrderUser.class);
            conditions.and().is("tradeNo",tradeNo);

            try {
                return dao.findJoinByCondition(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public Long countByTradeNo(String tradeNo){
        if(StringTools.isNotBlank(tradeNo)) {
            Conditions conditions = new Conditions(BusinessOrderUser.class);
            conditions.and().is("tradeNo",tradeNo);

            try {
                return dao.count(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return 0L;
    }

    public BusinessOrderUser getByKeys(String tradeNo,Long userId){
        if(StringTools.isNotBlank(tradeNo) && userId != null) {
            Conditions conditions = new Conditions(BusinessOrderUser.class);
            conditions.and().is("tradeNo",tradeNo);
            conditions.and().is("userId",userId);

            try {
                return dao.get(conditions);
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return null;
    }

    public boolean add(MemberBusinessOrder businessOrder,Long placeUserId) {
        Map<Long, BusinessOrderUser> data = new HashMap<>();
        //网点所属人
        BusinessOrderUser orderUser = new BusinessOrderUser();
        orderUser.setTradeNo(businessOrder.getTradeNo());
        orderUser.setDeviceFunCode(businessOrder.getDeviceFunCode());
        orderUser.setBusinessType(businessOrder.getBusinessType());
        orderUser.setUserId(placeUserId);
        orderUser.setRoleNames(ERoleType.Agent.note());
        orderUser.setPlaceId(businessOrder.getPlaceId());
        orderUser.setPlaceName(businessOrder.getPlaceName());
        orderUser.setPlaceUserId(placeUserId);
        orderUser.setProvince(businessOrder.getProvince());
        orderUser.setCity(businessOrder.getCity());
        orderUser.setCityArea(businessOrder.getCityArea());
        orderUser.setAreaCode(businessOrder.getAreaCode());
        orderUser.setState(businessOrder.getState());     //订单状态，用于查询
        orderUser.setCreateDate(businessOrder.getCreateDate());
        data.put(orderUser.getUserId(), orderUser);

        List<PlaceProfitUser> placeProfitUserList = PlaceProfitUserService.self().findByPlaceId(businessOrder.getPlaceId());
        if (placeProfitUserList != null && placeProfitUserList.size() > 0) {
            for (PlaceProfitUser placeProfitUser : placeProfitUserList) {
                orderUser = data.get(placeProfitUser.getUserId());
                if (orderUser != null) {
                    orderUser.setRoleNames(orderUser.getRoleNames() + "," + placeProfitUser.getRoleTypeName());
                } else {
                    orderUser = new BusinessOrderUser();
                    orderUser.setTradeNo(businessOrder.getTradeNo());
                    orderUser.setDeviceFunCode(businessOrder.getDeviceFunCode());
                    orderUser.setBusinessType(businessOrder.getBusinessType());
                    orderUser.setUserId(placeProfitUser.getUserId());
                    orderUser.setRoleNames(placeProfitUser.getRoleTypeName());
                    orderUser.setPlaceId(businessOrder.getPlaceId());
                    orderUser.setPlaceName(businessOrder.getPlaceName());
                    orderUser.setPlaceUserId(placeUserId);
                    orderUser.setProvince(businessOrder.getProvince());
                    orderUser.setCity(businessOrder.getCity());
                    orderUser.setCityArea(businessOrder.getCityArea());
                    orderUser.setAreaCode(businessOrder.getAreaCode());
                    orderUser.setState(businessOrder.getState());     //订单状态，用于查询
                    orderUser.setCreateDate(businessOrder.getCreateDate());
                    data.put(orderUser.getUserId(), orderUser);
                }
            }
        }
        if (add(new ArrayList<>(data.values()))) {
            return true;
        }
        return false;
    }

    public boolean add(List<BusinessOrderUser> orderUserList){
        try {
            return dao.insert(orderUserList) > 0;
        } catch (SQLException e) {
            log.error(e.getMessage(), e);
        }
        return false;
    }

    public boolean updateNotNull(BusinessOrderUser orderUser){
        if(StringTools.isNotBlank(orderUser.getTradeNo()) && orderUser.getUserId() != null){
            Conditions conditions = new Conditions(BusinessOrderUser.class);
            conditions.and().is("tradeNo", orderUser.getTradeNo());
            conditions.and().is("userId", orderUser.getUserId());

            try {
                return dao.updateNotNull(orderUser, conditions) > 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

    public boolean updateState(String tradeNo,Integer state){
        if(StringTools.isNotBlank(tradeNo) && state != null) {
            Conditions conditions = new Conditions(BusinessOrderUser.class);
            conditions.and().is("tradeNo",tradeNo);

            BusinessOrderUser updateEntity = new BusinessOrderUser();
            updateEntity.setState(state);

            try {
                return dao.updateNotNull(updateEntity,conditions) >= 0;
            } catch (SQLException e) {
                log.error(e.getMessage(), e);
            }
        }
        return false;
    }

    public boolean refresh(String tradeNo) throws LogicException {
        MemberBusinessOrder memberBusinessOrder = MemberBusinessOrderService.self(dao.getDate()).getByTradeNo(tradeNo);
        if(memberBusinessOrder != null){
            PlacePhysicalStore physicalStore = PlacePhysicalStoreService.self().getById(memberBusinessOrder.getPlaceId());
            if(physicalStore != null){
                boolean flag = true;
                Conditions conditions = new Conditions(BusinessOrderUser.class);
                conditions.and().is("tradeNo",tradeNo);

                try {
                    flag = dao.deleteByCondition(conditions) >= 0;
                } catch (SQLException e) {
                    log.error(e.getMessage(),e);
                }

                if(flag){
                    return add(memberBusinessOrder,physicalStore.getUserId());
                }
            }else{
                throw new LogicException("未找到网点信息，网点ID：" + memberBusinessOrder.getPlaceId());
            }
        }
        return false;
    }

}
